package com.bigseller.study;

import com.bigseller.study.model.User;
import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;



public class FreemarkTest {
    public static void main(String[] args) throws Exception {
        createHtmlFromModel();
    }

    /**
     * 使用模板生成HTML代码
     */
    public static void createHtmlFromModel() throws Exception{
        FileWriter out = null;
        try {
            // 通过FreeMarker的Confuguration读取相应的模板文件
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
            // 设置模板路径
            configuration.setClassForTemplateLoading(FreemarkTest.class, "/template");
            // 设置默认字体
            configuration.setDefaultEncoding("utf-8");

            configuration.setSharedVariable("barcodeTag", new TemplateDirectiveModel() {
                @Override
                public void execute(Environment env, Map params, TemplateModel[] templateModels, TemplateDirectiveBody body) throws TemplateException, IOException {
                    String name = params.get("name").toString();
                    String base64=name;
                    try {
                         base64 = GoogleBarCodeUtils.getBase64(name);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    env.setVariable("barcodeImage", getBeansWrapper().wrap(base64));

                    body.render(env.getOut());
                }
                public  BeansWrapper getBeansWrapper(){
                    BeansWrapper beansWrapper = new BeansWrapperBuilder(Configuration.VERSION_2_3_21).build();
                    return beansWrapper;
                }
            });


            // 获取模板
            Template template = configuration.getTemplate("user.ftl");
            //设置模型
            User user = new User("tom", "hahahah", 28, "上海市");

            //设置输出文件
            File file = new File("D:\\youdaoyun\\workspace_kafka\\kafka-study\\bar-code\\src\\main\\resources\\out/result.html");
            if(!file.exists()) {
                file.createNewFile();
            }
            //设置输出流
            out = new FileWriter(file);
            //模板输出静态文件
            template.process(user, out);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if(null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
